package com.skyaims.biz.factory.biz;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.skyaims.biz.factory.MessageProcessorFactory;
import com.skyaims.biz.message.Message;
import com.skyaims.biz.message.MessageType;
import com.skyaims.biz.message.ext.HeartBeatMessage;
import com.skyaims.biz.processor.HeartBeatProcessor;
import com.skyaims.biz.processor.MessageProcessor;
import com.skyaims.biz.util.Converter;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.nio.charset.Charset;

/**
 * Created by wujianing on 14-3-18.
 */
public abstract class AbsBusiness implements IBusiness, Runnable {

    public static final Logger log = LoggerFactory.getLogger(AbsBusiness.class);

    public static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");

    private ChannelHandlerContext ctx;

    private ChannelBuffer buff;

    public void required(ChannelHandlerContext ctx, ChannelBuffer buff) {
        this.ctx = ctx;
        this.buff = buff;
    }

    @Override
    public void run() {

        if (ctx == null || buff == null) {
            return;
        }

        if (buff.capacity() < 5) {
            return;
        }

        byte[] lengthBytes = new byte[4];
        byte[] flagBytes = new byte[1];
        buff.readBytes(lengthBytes);
        buff.readBytes(flagBytes);

        int length = Converter.bytesToInt(lengthBytes);
        int flag = Converter.bytesToInt(flagBytes);

        byte[] content = new byte[length];
        buff.readBytes(content);

        MessageType.MESSAGE_STRUCT_FLAG struct_flag = MessageType.MESSAGE_STRUCT_FLAG.values()[flag];

        switch (struct_flag) {
            case HEARTBEAT:
                HeartBeatMessage msg = new HeartBeatMessage();
                HeartBeatProcessor.process(msg);
                log.info("Receive HeartBeat Message From {} At {}", "", msg.getTimestamp());
                return;
            case UNCOMPRESSED:

                break;
            case COMPRESS:
                break;
        }

        String json = new String(content, DEFAULT_CHARSET);
        JSONObject jsonObject = JSON.parseObject(json);
        Integer action = jsonObject.getInteger("action");
        MessageProcessor processor = MessageProcessorFactory.getMessageProcessor(action);
        Message message = processor.parse(jsonObject);
        doBusiness(null, message);
        processor.process(message);

    }

}